Passed
Push — develop ( c592f3...b91919 )
by Endre
04:18
created

Router.attachTo   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
import {IObserver} from '../Observer/Observer';
2
3
export interface IPageData {
4
  name: string,
5
  rootUrl: string
6
  url: string,
7
  depth: number
8
}
9
10
export default class Router {
11
  currentPage: IObserver<IPageData | null>;
12
  history: History;
13
14
  constructor(pageObserver: IObserver<IPageData | null>, history: History) {
15 6
    this.currentPage = pageObserver;
16 6
    this.history = history;
17
  }
18
19
  attachTo(window: Window) {
20 3
    window.addEventListener('popstate', this.onHistoryChange.bind(this));
21
  }
22
23
  initialize(): void {
24 3
    if (this.currentPage.value == null) return;
25 1
    const firstPage: IPageData = this.currentPage.value;
26 1
    this.history.replaceState(firstPage, firstPage.name, firstPage.rootUrl);
27 1
    this.updatePage(firstPage);
28
  }
29
30
  changePage(newPage: IPageData): void {
31 2
    const currentPage: IPageData | null = this.currentPage.value;
32 4
    if (currentPage != null && currentPage.name == newPage.name) {
33 1
      return;
34
    }
35
36 1
    this.history.replaceState(newPage, newPage.name, newPage.url);
37 1
    this.updatePage(newPage);
38
  }
39
40
  updatePage(page: IPageData): void {
41 3
    this.currentPage.value = page;
42
  }
43
44
  onHistoryChange(event: PopStateEvent): void {
45 1
    const newPage: IPageData = event.state as IPageData;
46 1
    this.updatePage(newPage);
47
  }
48
}
49